package com.kakarote.common.log.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.kakarote.common.log.entity.OperateLogEntity;
import com.kakarote.common.log.service.MqMessageService;
import com.kakarote.common.log.service.OperateLogSaveService;
import com.kakarote.core.exception.CrmException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

/**
 * @author: admin
 * @version: v1.0
 * @date:2023/10/8
 */
@Service
@Slf4j
@ConditionalOnProperty(prefix = "wk.mq", name = "type", havingValue = "rocketmq")
public class RocketMqMessageServiceImpl implements MqMessageService, OperateLogSaveService {

    @Autowired
    private Producer producer;

    @Override
    public void send(String topic, Object message) {
        if (message instanceof Message) {
            send((Message) message, false);
        }
    }

    /**
     * 普通消息发送发放
     *
     * @param msg
     * @param isOneWay 是否单向发送
     * @return
     */
    private void send(Message msg, Boolean isOneWay) {
        try {
            if (isOneWay) {
                producer.sendOneway(msg);
            } else {
                SendResult sendResult = producer.send(msg);
                log.debug("发送普通消息成功，sendResult={}", sendResult);
            }
        } catch (Exception e) {
            throw new CrmException(500, "发送消息失败");
        }
    }

    /**
     * 保存操作日志
     *
     * @param entity entity
     */
    @Override
    public void saveOperateLog(OperateLogEntity.Entity.Builder entity) {
        Message msg = new Message(
                // 普通消息所属的Topic，切勿使用普通消息的Topic来收发其他类型的消息。
                "message",
                // Message Tag,
                "operateLog",
                // Message Body
                entity.build().toByteArray());
        send("message", msg);
    }
}
